<template>
  <div class="coordinate-editor" @click="handleClickOutside">
    <!-- 顶部导航栏 -->
    <header class="editor-header">
      <div class="header-container">
        <button class="back-btn" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </button>
        <h1 class="editor-title">{{ orginName || imageName }}</h1>
        <div class="header-actions">
          <button 
            class="simulation-btn" 
            :class="{ active: isSimulationMode }"
            @click="toggleSimulationMode"
          >
            <el-icon><VideoPlay /></el-icon>
            {{ isSimulationMode ? '退出模拟' : '模拟运行' }}
          </button>
          <button class="save-btn" @click="saveCoordinates">
            <el-icon><Check /></el-icon>
            保存
          </button>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <div class="editor-content">
      <!-- 左侧图片展示区域 -->
      <div class="image-container">
        <div 
          class="image-wrapper" 
          ref="imageWrapperRef"
          :class="{ 'draw-mode': isDrawMode }"
          @mousedown="handleImageMouseDown"
          @mousemove="handleImageMouseMove"
          @mouseup="handleImageMouseUp"
        >
          <img 
            :src="imageUrl" 
            :alt="imageName"
            class="main-image"
            @load="onImageLoad"
            ref="imageRef"
          />
          
          <!-- 坐标框覆盖层 -->
          <div 
            v-for="(button, index) in buttons" 
            :key="`btn_${index}`"
            class="coordinate-box"
            :style="getButtonStyle(button)"
            :class="{ 
              active: selectedButtonIndex === index,
              clickable: isSimulationMode && button.next,
              'no-next': isSimulationMode && !button.next
            }"
            @click.stop="handleButtonClick(button, index)"
            @mousedown="!isDrawMode && !isSimulationMode && startDrag(index, $event)"
           >
             <div class="button-label">{{ button.name || `控件${index + 1}` }}</div>
           </div>
          
          <!-- 绘制预览框 -->
          <div 
            v-if="drawState.previewButton"
            class="draw-preview-box"
            :style="getDrawPreviewStyle()"
          >
            <div class="draw-preview-label">新控件</div>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="properties-panel">
        <div class="panel-header">
          <h3>控件信息</h3>
          <div class="panel-actions" v-if="!isSimulationMode">
            <button class="add-button-btn" @click="addNewButton">
              <el-icon><Plus /></el-icon>
              添加控件
            </button>
            <button 
              class="draw-button-btn" 
              :class="{ active: isDrawMode }"
              @click="toggleDrawMode"
            >
              <el-icon><Edit /></el-icon>
              {{ isDrawMode ? '退出绘制' : '绘制控件' }}
            </button>
          </div>
        </div>
        
        <!-- 控件库按钮 -->
        <div v-if="!isSimulationMode" class="widget-library-section">
          <button class="widget-library-btn" @click="showWidgetLibrary">
            <el-icon><CollectionTag /></el-icon>
            控件库 ({{ widgetLibraryCount }})
          </button>
        </div>

        <div class="button-list" @click.stop>
          <div 
            v-for="(button, index) in buttons" 
            :key="`prop_${index}`"
            class="button-item"
            :class="{ active: selectedButtonIndex === index }"
            @click="selectButton(index)"
          >
            <div class="button-header">
              <span class="button-title">{{ button.name || `控件${index + 1}` }}</span>
              <button class="delete-button-btn" @click.stop="deleteButton(index)">
                <el-icon><Delete /></el-icon>
              </button>
            </div>

            <!-- 属性编辑表单 -->
            <div v-if="selectedButtonIndex === index" class="button-properties">
              <div class="property-group">
                <label>控件名称:</label>
                <el-input 
                  v-model="button.name" 
                  placeholder="输入控件名称"
                  size="small"
                />
              </div>

              <div class="property-group">
                <label>跳转页面:</label>
                <el-input 
                  v-model="button.next" 
                  placeholder="输入跳转页面名称"
                  size="small"
                />
              </div>

              <div class="coordinate-inputs">
                <div class="input-row">
                  <div class="input-group">
                    <label>X坐标:</label>
                    <el-input-number 
                      v-model="button.x" 
                      :min="0" 
                      :max="1366"
                      size="small"
                      @change="updateButtonPosition(index)"
                    />
                  </div>
                  <div class="input-group">
                    <label>Y坐标:</label>
                    <el-input-number 
                      v-model="button.y" 
                      :min="0" 
                      :max="728"
                      size="small"
                      @change="updateButtonPosition(index)"
                    />
                  </div>
                </div>

                <div class="input-row">
                  <div class="input-group">
                    <label>宽度:</label>
                    <el-input-number 
                      v-model="button.width" 
                      :min="10" 
                      :max="500"
                      size="small"
                      @change="updateButtonPosition(index)"
                    />
                  </div>
                  <div class="input-group">
                    <label>高度:</label>
                    <el-input-number 
                      v-model="button.height" 
                      :min="10" 
                      :max="200"
                      size="small"
                      @change="updateButtonPosition(index)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 控件库对话框 -->
    <el-dialog
      v-model="widgetLibraryVisible"
      title="控件库"
      width="600px"
      class="widget-library-dialog"
    >
      <div class="widget-library-content">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="widgetSearchKeyword"
            placeholder="搜索控件名称..."
            clearable
            size="large"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 控件列表 -->
        <div class="widget-list">
          <div 
            v-for="(widget, index) in filteredWidgets" 
            :key="index"
            class="widget-item"
            :class="{ selected: selectedWidgetIndex === index }"
            @click="selectWidget(index)"
          >
            <div class="widget-info">
              <div class="widget-name">{{ widget.name || '未命名控件' }}</div>
              <div class="widget-details">
                <span class="widget-size">{{ widget.width }}×{{ widget.height }}</span>
                <span class="widget-position">位置: ({{ widget.x }}, {{ widget.y }})</span>
                <!-- <span class="widget-count">出现 {{ widget.count }} 次</span>
                <span v-if="widget.next" class="widget-next">→ {{ widget.next }}</span> -->
              </div>
            </div>
          </div>
          
          <div v-if="filteredWidgets.length === 0" class="empty-widget">
            <el-empty description="没有找到匹配的控件" />
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="widgetLibraryVisible = false" size="large">取消</el-button>
          <el-button 
            type="primary" 
            @click="applyWidget" 
            :disabled="selectedWidgetIndex === -1"
            size="large"
          >
            应用控件
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 智能删除对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除控件"
      width="600px"
      class="delete-dialog"
    >
      <div class="delete-dialog-content">
        <div class="delete-info">
          <el-icon class="warning-icon"><WarningFilled /></el-icon>
          <div class="delete-text">
            <p class="main-text">确定要删除控件 "<strong>{{ buttonToDelete?.name }}</strong>" 吗？</p>
          </div>
        </div>
        
        <el-divider />
        
        <div class="delete-options">
          <el-radio-group v-model="deleteMode" class="delete-radio-group">
            <el-radio value="current" class="delete-radio">
              <div class="radio-content">
                <div class="radio-title">仅删除当前界面</div>
                <div class="radio-desc">只删除当前页面的这个控件</div>
              </div>
            </el-radio>
            
            <!-- 注释掉选择性删除功能 -->
            <!-- <el-radio value="selective" class="delete-radio">
              <div class="radio-content">
                <div class="radio-title">选择性删除指定界面</div>
                <div class="radio-desc">搜索并选择要删除的页面</div>
              </div>
            </el-radio> -->
            
            <el-radio value="all" class="delete-radio">
              <div class="radio-content">
                <div class="radio-title">批量删除所有界面</div>
                <div class="radio-desc">删除所有 {{ relatedPages.length }} 个页面中的该控件</div>
              </div>
            </el-radio>
          </el-radio-group>
          
          <!-- 注释掉选择性删除模式的页面搜索区域 -->
          <!-- <div v-if="deleteMode === 'selective'" class="page-selector">
            <div class="selector-header">
              <el-input
                v-model="pageSearchKeyword"
                placeholder="搜索页面名称..."
                clearable
                size="default"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            
            <div class="page-list-container">
              <div 
                v-for="page in filteredPages" 
                :key="page.pageKey"
                class="page-item"
                :class="{ 
                  current: page.isCurrent,
                  selected: selectedPages.includes(page.pageKey)
                }"
                @click="togglePageSelection(page.pageKey)"
              >
                <el-checkbox 
                  :model-value="selectedPages.includes(page.pageKey)"
                  @click.stop
                />
                <div class="page-item-info">
                  <span class="page-name">{{ page.pageName }}</span>
                  <span v-if="page.isCurrent" class="current-badge">当前</span>
                </div>
              </div>
              
              <div v-if="filteredPages.length === 0" class="empty-pages">
                <el-empty description="没有找到匹配的页面" :image-size="60" />
              </div>
            </div>
            
            <div class="selector-footer">
              <span class="selected-count">已选择 {{ selectedPages.length }} 个页面</span>
              <el-button 
                text 
                size="small" 
                @click="selectAllPages"
                v-if="filteredPages.length > 0"
              >
                全选
              </el-button>
              <el-button 
                text 
                size="small" 
                @click="clearPageSelection"
                v-if="selectedPages.length > 0"
              >
                清空
              </el-button>
            </div>
          </div> -->
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false" size="large">取消</el-button>
          <el-button 
            type="danger" 
            @click="executeDelete"
            size="large"
          >
            确认删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 坐标编辑器组件
 * 
 * 功能：
 * - 显示设备图片
 * - 可视化编辑按钮坐标
 * - 拖拽和调整按钮大小
 * - 保存坐标信息
 */

import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDeviceStore } from '@/stores/device'

console.log('坐标编辑器组件加载')

const route = useRoute()
const router = useRouter()
const deviceStore = useDeviceStore()

// 响应式数据
const imageName = ref(route.query.imageName || '')
const imageUrl = ref(route.query.imageUrl || '')
const orginName = ref(route.query.orginName || '')
const buttons = ref([])
const selectedButtonIndex = ref(-1)
const imageWrapperRef = ref(null)
const imageRef = ref(null)
const deviceId = ref(route.params.deviceId || '')
const imageId = ref(route.params.imageId || '')
const selectedDevice = ref(null)

// 拖拽相关状态
const dragState = reactive({
  isDragging: false,
  isResizing: false,
  startX: 0,
  startY: 0,
  startButtonX: 0,
  startButtonY: 0,
  startButtonWidth: 0,
  startButtonHeight: 0,
  resizeDirection: '',
  dragButtonIndex: -1
})

// 绘制模式状态
const isDrawMode = ref(false)
const drawState = reactive({
  isDrawing: false,
  startX: 0,
  startY: 0,
  currentX: 0,
  currentY: 0,
  previewButton: null
})

// 模拟模式状态
const isSimulationMode = ref(false)
const simulationState = reactive({
  currentPageKey: '',
  allCoordinateData: {},
  currentPageData: null,
  availablePages: []
})

// 控件库相关状态
const widgetLibraryVisible = ref(false)
const widgetSearchKeyword = ref('')
const selectedWidgetIndex = ref(-1)

// 删除控件对话框相关状态
const deleteDialogVisible = ref(false)
const deleteButtonIndex = ref(-1)
const deleteMode = ref('current') // 'current', 'selective', 'all'
const buttonToDelete = ref(null)
const relatedPages = ref([]) // 该控件出现的其他页面
const pageSearchKeyword = ref('') // 页面搜索关键词
const selectedPages = ref([]) // 用户选择要删除的页面

// 图片缩放比例
const imageScale = ref(1)

// 初始化坐标数据
const initializeCoordinates = () => {
  try {
    // 解析设备数据
    if (route.query.deviceData) {
      selectedDevice.value = JSON.parse(route.query.deviceData)
      console.log('接收到设备数据:', selectedDevice.value)
    }
    
    const coordinateData = JSON.parse(route.query.coordinateData || '{}')
    console.log('初始化坐标数据:', coordinateData)
    
    if (coordinateData.buttons && Array.isArray(coordinateData.buttons)) {
      buttons.value = coordinateData.buttons.map(btn => ({
        name: btn.name || '',
        next: btn.next || '',
        x: btn.x || 0,
        y: btn.y || 0,
        width: btn.width || 100,
        height: btn.height || 40
      }))
    }
    
    // 初始化所有坐标数据（用于智能删除功能）
    if (selectedDevice.value && selectedDevice.value.coordinateLog) {
      try {
        const logContent = selectedDevice.value.coordinateLog.content
        simulationState.allCoordinateData = deviceStore.parseLogContent(logContent)
        
        // 设置当前页面键
        const currentPageKey = imageName.value.replace(/\.[^/.]+$/, "")
        simulationState.currentPageKey = currentPageKey
        
        console.log('已加载所有页面坐标数据，页面数量:', Object.keys(simulationState.allCoordinateData).length)
      } catch (error) {
        console.warn('加载全部坐标数据失败:', error)
      }
    }
  } catch (error) {
    console.error('解析坐标数据失败:', error)
    ElMessage.error('坐标数据解析失败')
  }
}

// 图片加载完成
const onImageLoad = () => {
  console.log('图片加载完成')
  nextTick(() => {
    calculateImageScale()
  })
}

// 计算图片缩放比例
const calculateImageScale = () => {
  if (!imageRef.value) return
  
  const img = imageRef.value
  const naturalWidth = img.naturalWidth
  const naturalHeight = img.naturalHeight
  const displayWidth = img.clientWidth
  const displayHeight = img.clientHeight
  
  // 计算缩放比例（以宽度为准）
  imageScale.value = displayWidth / naturalWidth
  console.log('图片缩放比例:', imageScale.value, '原始尺寸:', naturalWidth, 'x', naturalHeight, '显示尺寸:', displayWidth, 'x', displayHeight)
}

// 获取按钮样式
const getButtonStyle = (button) => {
  return {
    left: `${button.x * imageScale.value}px`,
    top: `${button.y * imageScale.value}px`,
    width: `${button.width * imageScale.value}px`,
    height: `${button.height * imageScale.value}px`
  }
}

// 选择按钮
const selectButton = (index) => {
  selectedButtonIndex.value = index
  console.log('选择按钮:', index)
}

// 处理点击空白处
const handleClickOutside = () => {
  if (selectedButtonIndex.value !== -1) {
    selectedButtonIndex.value = -1
    console.log('取消选择按钮')
  }
}

// 切换绘制模式
const toggleDrawMode = () => {
  isDrawMode.value = !isDrawMode.value
  
  if (isDrawMode.value) {
    // 进入绘制模式
    selectedButtonIndex.value = -1
    drawState.isDrawing = false
    drawState.previewButton = null
    ElMessage.info('进入绘制模式，在图片上拖拽绘制控件区域')
  } else {
    // 退出绘制模式
    drawState.isDrawing = false
    drawState.previewButton = null
    ElMessage.success('退出绘制模式')
  }
}

// 切换模拟模式
const toggleSimulationMode = async () => {
  if (!isSimulationMode.value) {
    // 进入模拟模式
    try {
      await initializeSimulationMode()
      isSimulationMode.value = true
      isDrawMode.value = false // 退出绘制模式
      selectedButtonIndex.value = -1 // 取消选择
      ElMessage.success('进入模拟模式，点击控件可以跳转页面')
    } catch (error) {
      ElMessage.error('进入模拟模式失败：' + error.message)
    }
  } else {
    // 退出模拟模式
    isSimulationMode.value = false
    // 恢复到当前页面
    await loadPageData(simulationState.currentPageKey)
    ElMessage.success('退出模拟模式')
  }
}

// 初始化模拟模式
const initializeSimulationMode = async () => {
  try {
    // 获取所有坐标数据
    if (!selectedDevice.value || !selectedDevice.value.coordinateLog) {
      throw new Error('没有找到坐标数据')
    }
    
    const logContent = selectedDevice.value.coordinateLog.content
    simulationState.allCoordinateData = deviceStore.parseLogContent(logContent)
    
    // 设置当前页面
    const currentPageKey = imageName.value.replace(/\.[^/.]+$/, "")
    simulationState.currentPageKey = currentPageKey
    
    // 获取所有可用页面
    simulationState.availablePages = Object.keys(simulationState.allCoordinateData)
    
    console.log('模拟模式初始化完成')
    console.log('当前页面:', currentPageKey)
    console.log('可用页面:', simulationState.availablePages)
    console.log('所有坐标数据:', simulationState.allCoordinateData)
    
  } catch (error) {
    console.error('初始化模拟模式失败:', error)
    throw error
  }
}

// 处理按钮点击
const handleButtonClick = (button, index) => {
  if (isSimulationMode.value) {
    // 模拟模式下处理页面跳转
    handlePageNavigation(button)
  } else if (isDrawMode.value) {
    // 绘制模式下不处理点击
    return
  } else {
    // 编辑模式下选择按钮
    selectButton(index)
  }
}

// 处理页面导航
const handlePageNavigation = async (button) => {
  if (!button.next) {
    ElMessage.warning(`控件"${button.name}"没有设置跳转页面`)
    return
  }
  
  console.log(`点击按钮"${button.name}"，跳转到页面: ${button.next}`)
  
  try {
    await loadPageData(button.next)
    ElMessage.info(`已跳转到页面: ${button.next}`)
  } catch (error) {
    ElMessage.error(`跳转失败: ${error.message}`)
  }
}

// 加载页面数据
const loadPageData = async (pageKey) => {
  try {
    console.log('加载页面数据:', pageKey)
    
    // 检查页面是否存在
    if (!simulationState.allCoordinateData[pageKey]) {
      throw new Error(`页面 "${pageKey}" 不存在`)
    }
    
    const pageData = simulationState.allCoordinateData[pageKey]
    
    if (!Array.isArray(pageData) || pageData.length === 0) {
      throw new Error(`页面 "${pageKey}" 数据格式错误`)
    }
    
    // 更新当前页面
    simulationState.currentPageKey = pageKey
    simulationState.currentPageData = pageData
    
    // 提取页面信息和按钮
    const pageInfo = pageData[0]
    const pageButtons = pageData.slice(1).filter(btn => 
      btn && 
      typeof btn === 'object' && 
      btn.x !== undefined && 
      btn.y !== undefined &&
      btn.width !== undefined &&
      btn.height !== undefined
    )
    
    // 更新按钮数据
    buttons.value = pageButtons.map(btn => ({
      name: btn.name || '',
      next: btn.next || '',
      x: btn.x || 0,
      y: btn.y || 0,
      width: btn.width || 100,
      height: btn.height || 40
    }))
    
    // 更新页面标题
    orginName.value = pageInfo.orgin_name || pageKey
    
    // 尝试加载对应的图片
    await loadPageImage(pageKey)
    
    console.log(`页面 "${pageKey}" 加载完成，按钮数量: ${buttons.value.length}`)
    
  } catch (error) {
    console.error('加载页面数据失败:', error)
    throw error
  }
}

// 加载页面图片
const loadPageImage = async (pageKey) => {
  try {
    // 查找对应的图片
    if (selectedDevice.value && selectedDevice.value.images) {
      const matchingImage = selectedDevice.value.images.find(img => {
        const imgNameWithoutExt = img.name.replace(/\.[^/.]+$/, "")
        return imgNameWithoutExt === pageKey || 
               imgNameWithoutExt.toLowerCase() === pageKey.toLowerCase() ||
               img.name === pageKey ||
               img.name.toLowerCase() === pageKey.toLowerCase()
      })
      
      if (matchingImage) {
        imageUrl.value = matchingImage.url || matchingImage.thumbnail
        imageName.value = matchingImage.name
        console.log(`找到匹配图片: ${matchingImage.name}`)
        
        // 等待图片加载
        await nextTick()
        if (imageRef.value) {
          await new Promise((resolve) => {
            if (imageRef.value.complete) {
              resolve()
            } else {
              imageRef.value.onload = resolve
            }
          })
          calculateImageScale()
        }
      } else {
        console.warn(`未找到页面 "${pageKey}" 对应的图片`)
      }
    }
  } catch (error) {
    console.error('加载页面图片失败:', error)
  }
}

// 控件库数量
const widgetLibraryCount = computed(() => {
  return deviceStore.widgetLibrary?.length || 0
})

// 过滤后的控件列表
const filteredWidgets = computed(() => {
  if (!deviceStore.widgetLibrary) return []
  
  const keyword = widgetSearchKeyword.value.trim().toLowerCase()
  if (!keyword) {
    return deviceStore.widgetLibrary
  }
  
  return deviceStore.widgetLibrary.filter(widget => {
    return widget.name.toLowerCase().includes(keyword) ||
           widget.next.toLowerCase().includes(keyword)
  })
})

// 注释掉选择性删除相关功能
// // 过滤后的页面列表（用于选择性删除）
// const filteredPages = computed(() => {
//   if (!relatedPages.value || relatedPages.value.length === 0) return []
//   
//   const keyword = pageSearchKeyword.value.trim().toLowerCase()
//   if (!keyword) {
//     return relatedPages.value
//   }
//   
//   return relatedPages.value.filter(page => {
//     return page.pageName.toLowerCase().includes(keyword) ||
//            page.pageKey.toLowerCase().includes(keyword)
//   })
// })

// // 切换页面选择
// const togglePageSelection = (pageKey) => {
//   const index = selectedPages.value.indexOf(pageKey)
//   if (index > -1) {
//     selectedPages.value.splice(index, 1)
//   } else {
//     selectedPages.value.push(pageKey)
//   }
// }

// // 全选页面
// const selectAllPages = () => {
//   selectedPages.value = filteredPages.value.map(p => p.pageKey)
// }

// // 清空选择
// const clearPageSelection = () => {
//   selectedPages.value = []
// }

// 显示控件库
const showWidgetLibrary = () => {
  if (!deviceStore.widgetLibrary || deviceStore.widgetLibrary.length === 0) {
    ElMessage.warning('控件库为空，请先在主页面点击"导入"按钮构建控件库')
    return
  }
  
  widgetLibraryVisible.value = true
  widgetSearchKeyword.value = ''
  selectedWidgetIndex.value = -1
}

// 选择控件
const selectWidget = (index) => {
  selectedWidgetIndex.value = index
  console.log('选择控件:', filteredWidgets.value[index])
}

// 应用控件
const applyWidget = () => {
  if (selectedWidgetIndex.value === -1) return
  
  const widget = filteredWidgets.value[selectedWidgetIndex.value]
  
  console.log('应用控件:', widget)
  console.log('控件原始坐标:', widget.x, widget.y)
  console.log('控件所有出现位置:', widget.coordinates)
  
  // 使用控件第一次出现时的原始坐标
  // 确保坐标在有效范围内
  const x = Math.max(0, Math.min(1366 - widget.width, widget.x))
  const y = Math.max(0, Math.min(728 - widget.height, widget.y))
  
  const newButton = {
    name: widget.name,
    next: widget.next,
    x: x,
    y: y,
    width: widget.width,
    height: widget.height
  }
  
  buttons.value.push(newButton)
  selectedButtonIndex.value = buttons.value.length - 1
  
  // 关闭对话框
  widgetLibraryVisible.value = false
  
  ElMessage.success(`成功添加控件: ${widget.name} (位置: ${x}, ${y})`)
}

// 添加新按钮
const addNewButton = () => {
  const newButton = {
    name: `控件${buttons.value.length + 1}`,
    next: '',
    x: 100,
    y: 100,
    width: 120,
    height: 40
  }
  
  buttons.value.push(newButton)
  selectedButtonIndex.value = buttons.value.length - 1
  
  ElMessage.success('添加控件成功')
}

// 查找控件在所有页面中的出现位置
const findButtonInAllPages = (button) => {
  const pages = []
  
  if (!simulationState.allCoordinateData || Object.keys(simulationState.allCoordinateData).length === 0) {
    return pages
  }
  
  // 生成控件的唯一标识
  const buttonKey = `${button.name}_${button.width}x${button.height}_${button.next}`
  
  // 遍历所有页面
  for (const [pageKey, pageData] of Object.entries(simulationState.allCoordinateData)) {
    if (Array.isArray(pageData) && pageData.length > 1) {
      // 检查该页面是否有相同的控件
      const buttons = pageData.slice(1).filter(btn => 
        btn && 
        typeof btn === 'object' && 
        btn.x !== undefined && 
        btn.y !== undefined
      )
      
      const hasMatchingButton = buttons.some(btn => {
        const btnKey = `${btn.name}_${btn.width}x${btn.height}_${btn.next}`
        return btnKey === buttonKey
      })
      
      if (hasMatchingButton) {
        const pageInfo = pageData[0]
        pages.push({
          pageKey: pageKey,
          pageName: pageInfo.orgin_name || pageKey,
          isCurrent: pageKey === simulationState.currentPageKey
        })
      }
    }
  }
  
  return pages
}

// 删除按钮 - 显示智能删除对话框
const deleteButton = (index) => {
  const button = buttons.value[index]
  
  // 查找该控件在其他页面的出现情况
  const pages = findButtonInAllPages(button)
  
  console.log('控件信息:', button)
  console.log('出现的页面:', pages)
  
  // 保存待删除的控件信息
  deleteButtonIndex.value = index
  buttonToDelete.value = button
  relatedPages.value = pages
  deleteMode.value = 'current'
  pageSearchKeyword.value = ''
  selectedPages.value = []
  
  // 显示删除对话框
  deleteDialogVisible.value = true
}

// 执行删除操作
const executeDelete = async () => {
  try {
    const button = buttonToDelete.value
    const currentPageKey = imageName.value.replace(/\.[^/.]+$/, "")
    const buttonKey = `${button.name}_${button.width}x${button.height}_${button.next}`
    
    console.log('执行删除操作，模式:', deleteMode.value)
    console.log('当前页面:', currentPageKey)
    
    if (deleteMode.value === 'current') {
      // 只删除当前界面的控件
      buttons.value.splice(deleteButtonIndex.value, 1)
      if (selectedButtonIndex.value >= deleteButtonIndex.value) {
        selectedButtonIndex.value = selectedButtonIndex.value > 0 ? selectedButtonIndex.value - 1 : -1
      }
      ElMessage.success('已删除当前界面的控件')
      
    // 注释掉选择性删除功能
    // } else if (deleteMode.value === 'selective') {
    //   // 选择性删除指定页面的控件
    //   if (selectedPages.value.length === 0) {
    //     ElMessage.warning('请先选择要删除的页面')
    //     return
    //   }
    //   
    //   let deletedCount = 0
    //   
    //   // 只删除选中的页面
    //   for (const selectedPageKey of selectedPages.value) {
    //     const pageData = simulationState.allCoordinateData[selectedPageKey]
    //     if (Array.isArray(pageData) && pageData.length > 1) {
    //       const originalLength = pageData.length
    //       
    //       // 过滤掉匹配的控件
    //       const filteredData = [pageData[0]] // 保留页面信息
    //       pageData.slice(1).forEach(btn => {
    //         if (btn && typeof btn === 'object') {
    //           const btnKey = `${btn.name}_${btn.width}x${btn.height}_${btn.next}`
    //           if (btnKey !== buttonKey) {
    //             filteredData.push(btn)
    //           }
    //         }
    //       })
    //       
    //       if (filteredData.length < originalLength) {
    //         simulationState.allCoordinateData[selectedPageKey] = filteredData
    //         deletedCount++
    //       }
    //     }
    //   }
    //   
    //   // 如果当前页面在选中列表中，也从当前页面删除
    //   if (selectedPages.value.includes(currentPageKey)) {
    //     buttons.value.splice(deleteButtonIndex.value, 1)
    //     if (selectedButtonIndex.value >= deleteButtonIndex.value) {
    //       selectedButtonIndex.value = selectedButtonIndex.value > 0 ? selectedButtonIndex.value - 1 : -1
    //     }
    //   }
    //   
    //   ElMessage.success(`已从 ${deletedCount} 个选中页面删除该控件`)
      
    } else if (deleteMode.value === 'all') {
      // 删除所有界面的该控件
      let deletedCount = 0
      
      // 遍历所有页面数据
      for (const [pageKey, pageData] of Object.entries(simulationState.allCoordinateData)) {
        if (Array.isArray(pageData) && pageData.length > 1) {
          const originalLength = pageData.length
          
          // 过滤掉匹配的控件
          const filteredData = [pageData[0]] // 保留页面信息
          pageData.slice(1).forEach(btn => {
            if (btn && typeof btn === 'object') {
              const btnKey = `${btn.name}_${btn.width}x${btn.height}_${btn.next}`
              if (btnKey !== buttonKey) {
                filteredData.push(btn)
              }
            }
          })
          
          if (filteredData.length < originalLength) {
            simulationState.allCoordinateData[pageKey] = filteredData
            deletedCount++
          }
        }
      }
      
      // 从当前页面删除
      buttons.value.splice(deleteButtonIndex.value, 1)
      if (selectedButtonIndex.value >= deleteButtonIndex.value) {
        selectedButtonIndex.value = selectedButtonIndex.value > 0 ? selectedButtonIndex.value - 1 : -1
      }
      
      ElMessage.success(`已从 ${deletedCount} 个页面删除该控件`)
    }
    
    // 关闭对话框
    deleteDialogVisible.value = false
    
  } catch (error) {
    console.error('删除控件失败:', error)
    ElMessage.error('删除失败：' + error.message)
  }
}

// 更新按钮位置（输入框改变时调用）
const updateButtonPosition = (index) => {
  // 强制重新渲染
  buttons.value = [...buttons.value]
}

// 获取绘制预览框样式
const getDrawPreviewStyle = () => {
  if (!drawState.previewButton) return {}
  
  return {
    left: `${drawState.previewButton.x * imageScale.value}px`,
    top: `${drawState.previewButton.y * imageScale.value}px`,
    width: `${drawState.previewButton.width * imageScale.value}px`,
    height: `${drawState.previewButton.height * imageScale.value}px`
  }
}

// 获取鼠标在图片上的坐标
const getImageCoordinates = (event) => {
  if (!imageRef.value) return { x: 0, y: 0 }
  
  const rect = imageRef.value.getBoundingClientRect()
  const x = (event.clientX - rect.left) / imageScale.value
  const y = (event.clientY - rect.top) / imageScale.value
  
  return {
    x: Math.max(0, Math.min(1366, x)),
    y: Math.max(0, Math.min(728, y))
  }
}

// 图片鼠标按下事件
const handleImageMouseDown = (event) => {
  if (!isDrawMode.value) return
  
  const coords = getImageCoordinates(event)
  
  drawState.isDrawing = true
  drawState.startX = coords.x
  drawState.startY = coords.y
  drawState.currentX = coords.x
  drawState.currentY = coords.y
  
  // 创建预览按钮
  drawState.previewButton = {
    x: coords.x,
    y: coords.y,
    width: 0,
    height: 0
  }
  
  event.preventDefault()
}

// 图片鼠标移动事件
const handleImageMouseMove = (event) => {
  if (!isDrawMode.value || !drawState.isDrawing) return
  
  const coords = getImageCoordinates(event)
  
  drawState.currentX = coords.x
  drawState.currentY = coords.y
  
  // 更新预览按钮
  if (drawState.previewButton) {
    const minX = Math.min(drawState.startX, drawState.currentX)
    const minY = Math.min(drawState.startY, drawState.currentY)
    const maxX = Math.max(drawState.startX, drawState.currentX)
    const maxY = Math.max(drawState.startY, drawState.currentY)
    
    drawState.previewButton.x = minX
    drawState.previewButton.y = minY
    drawState.previewButton.width = maxX - minX
    drawState.previewButton.height = maxY - minY
  }
}

// 图片鼠标释放事件
const handleImageMouseUp = (event) => {
  if (!isDrawMode.value || !drawState.isDrawing) return
  
  drawState.isDrawing = false
  
  if (drawState.previewButton) {
    const { x, y, width, height } = drawState.previewButton
    
    // 检查绘制的区域是否有效（最小尺寸）
    if (width >= 10 && height >= 10) {
      // 创建新按钮
      const newButton = {
        name: `控件${buttons.value.length + 1}`,
        next: '',
        x: Math.round(x),
        y: Math.round(y),
        width: Math.round(width),
        height: Math.round(height)
      }
      
      buttons.value.push(newButton)
      selectedButtonIndex.value = buttons.value.length - 1
      
      ElMessage.success(`创建控件成功 (${Math.round(x)}, ${Math.round(y)}, ${Math.round(width)}x${Math.round(height)})`)
    } else {
      ElMessage.warning('绘制区域太小，请重新绘制')
    }
  }
  
  // 清除预览
  drawState.previewButton = null
}

// 开始拖拽
const startDrag = (index, event) => {
  if (dragState.isResizing) return
  
  dragState.isDragging = true
  dragState.dragButtonIndex = index
  dragState.startX = event.clientX
  dragState.startY = event.clientY
  dragState.startButtonX = buttons.value[index].x
  dragState.startButtonY = buttons.value[index].y
  
  selectedButtonIndex.value = index
  
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
  
  event.preventDefault()
}

// 拖拽中
const onDrag = (event) => {
  if (!dragState.isDragging) return
  
  const deltaX = (event.clientX - dragState.startX) / imageScale.value
  const deltaY = (event.clientY - dragState.startY) / imageScale.value
  
  const button = buttons.value[dragState.dragButtonIndex]
  button.x = Math.max(0, Math.min(1366 - button.width, dragState.startButtonX + deltaX))
  button.y = Math.max(0, Math.min(728 - button.height, dragState.startButtonY + deltaY))
}

// 停止拖拽
const stopDrag = () => {
  dragState.isDragging = false
  dragState.dragButtonIndex = -1
  
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 开始调整大小
const startResize = (index, direction, event) => {
  dragState.isResizing = true
  dragState.dragButtonIndex = index
  dragState.resizeDirection = direction
  dragState.startX = event.clientX
  dragState.startY = event.clientY
  
  const button = buttons.value[index]
  dragState.startButtonX = button.x
  dragState.startButtonY = button.y
  dragState.startButtonWidth = button.width
  dragState.startButtonHeight = button.height
  
  selectedButtonIndex.value = index
  
  document.addEventListener('mousemove', onResize)
  document.addEventListener('mouseup', stopResize)
  
  event.preventDefault()
}

// 调整大小中
const onResize = (event) => {
  if (!dragState.isResizing) return
  
  const deltaX = (event.clientX - dragState.startX) / imageScale.value
  const deltaY = (event.clientY - dragState.startY) / imageScale.value
  
  const button = buttons.value[dragState.dragButtonIndex]
  const direction = dragState.resizeDirection
  
  if (direction.includes('e')) {
    button.width = Math.max(10, Math.min(500, dragState.startButtonWidth + deltaX))
  }
  if (direction.includes('w')) {
    const newWidth = Math.max(10, dragState.startButtonWidth - deltaX)
    const widthDiff = newWidth - button.width
    button.x = Math.max(0, dragState.startButtonX - widthDiff)
    button.width = newWidth
  }
  if (direction.includes('s')) {
    button.height = Math.max(10, Math.min(200, dragState.startButtonHeight + deltaY))
  }
  if (direction.includes('n')) {
    const newHeight = Math.max(10, dragState.startButtonHeight - deltaY)
    const heightDiff = newHeight - button.height
    button.y = Math.max(0, dragState.startButtonY - heightDiff)
    button.height = newHeight
  }
}

// 停止调整大小
const stopResize = () => {
  dragState.isResizing = false
  dragState.dragButtonIndex = -1
  dragState.resizeDirection = ''
  
  document.removeEventListener('mousemove', onResize)
  document.removeEventListener('mouseup', stopResize)
}

// 保存坐标
const saveCoordinates = async () => {
  try {
    console.log('开始保存坐标信息:', buttons.value)
    
    // 构造当前页面的坐标信息对象
    const coordinateInfo = {
      orgin_name: orginName.value,
      buttons: buttons.value.map(btn => ({
        next: btn.next || '',
        name: btn.name || '',
        x: Math.round(btn.x),
        y: Math.round(btn.y),
        width: Math.round(btn.width),
        height: Math.round(btn.height)
      }))
    }
    
    // 从图片名称推导页面键
    const imageNameWithoutExt = imageName.value.replace(/\.[^/.]+$/, "")
    const pageKey = imageNameWithoutExt
    
    // 更新当前页面在allCoordinateData中的数据
    if (simulationState.allCoordinateData[pageKey]) {
      const newPageData = [
        { orgin_name: coordinateInfo.orgin_name }
      ]
      coordinateInfo.buttons.forEach(btn => {
        newPageData.push(btn)
      })
      simulationState.allCoordinateData[pageKey] = newPageData
    }
    
    console.log('保存页面键:', pageKey, '坐标信息:', coordinateInfo)
    
    // 如果进行了批量删除，需要保存所有修改过的页面
    if (selectedDevice.value && selectedDevice.value.coordinateLog) {
      try {
        // 将修改后的所有坐标数据写回设备
        const updatedLogContent = JSON.stringify(simulationState.allCoordinateData, null, 2)
        selectedDevice.value.coordinateLog.content = updatedLogContent
        
        console.log('已更新设备的坐标日志数据')
      } catch (error) {
        console.warn('更新坐标日志数据失败:', error)
      }
    }
    
    // 调用Store方法保存当前页面
    await deviceStore.saveCoordinatesToLog(deviceId.value, pageKey, coordinateInfo)
    
    ElMessage.success('坐标保存成功')
    
  } catch (error) {
    console.error('保存坐标失败:', error)
    ElMessage.error('保存坐标失败：' + error.message)
  }
}

// 返回
const goBack = () => {
  // 返回到设备图片展示页面，保持编辑状态
  router.push({
    name: 'Home',
    query: {
      deviceId: deviceId.value,
      editMode: 'true',
      coordinatesImported: 'true'
    }
  })
}

// 生命周期
onMounted(() => {
  console.log('坐标编辑器挂载，路由参数:', route.params, route.query)
  initializeCoordinates()
  
  // 监听窗口大小变化
  window.addEventListener('resize', calculateImageScale)
})
</script>

<style scoped>
/* 整体布局 */
.coordinate-editor {
  width: 100vw;
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部导航栏 */
.editor-header {
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  height: 60px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: clamp(8px, 1vw, 12px) clamp(16px, 2vw, 24px);
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #ffffff;
  color: #333333;
  font-size: clamp(12px, 1vw, 16px);
  cursor: pointer;
  transition: all 0.2s ease;
}

.back-btn:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #ccc;
}

.editor-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

.save-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: clamp(8px, 1vw, 12px) clamp(16px, 2vw, 24px);
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #ffffff;
  color: #333333;
  font-size: clamp(12px, 1vw, 16px);
  cursor: pointer;
  transition: all 0.2s ease;
}

.simulation-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: clamp(8px, 1vw, 12px) clamp(16px, 2vw, 24px);
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #ffffff;
  color: #333333;
  font-size: clamp(12px, 1vw, 16px);
  cursor: pointer;
  transition: all 0.2s ease;
}

.simulation-btn:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #ccc;
}

.simulation-btn.active {
  background: #ffebee;
  border-color: #f44336;
  color: #f44336;
}

.simulation-btn.active:hover {
  background: #ffcdd2;
  border-color: #f44336;
  color: #f44336;
}

.save-btn:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #ccc;
}

/* 主要内容区域 */
.editor-content {
  flex: 1;
  display: flex;
  min-height: 0;
}

/* 左侧图片容器 */
.image-container {
  flex: 1;
  background: #ffffff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  /*justify-content: center;*/
  padding: 20px;
  overflow: auto;
}

.image-wrapper {
  position: relative;
  min-width: 1366px;
  min-height: 728px;
  border: 2px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
  background: #fafafa;
}

.main-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

/* 坐标框 */
.coordinate-box {
  position: absolute;
  border: 2px solid #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
  cursor: move;
  transition: all 0.2s ease;
  min-width: 10px;
  min-height: 10px;
}

.coordinate-box:hover,
.coordinate-box.active {
  border-color: #1890ff;
  background: rgba(24, 144, 255, 0.1);
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.button-label {
  position: absolute;
  top: -24px;
  left: 0;
  background: #999999;
  color: white;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 10px;
  white-space: nowrap;
  pointer-events: none;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.coordinate-box:hover .button-label {
  opacity: 1;
}

.coordinate-box.active .button-label {
  background: #1890ff;
  opacity: 1;
}

/* 模拟模式下的按钮样式 */
.coordinate-box.clickable {
  cursor: pointer;
  border-color: #f44336;
  background: rgba(244, 67, 54, 0.1);
  transition: all 0.2s ease;
}

.coordinate-box.clickable:hover {
  border-color: #d32f2f;
  background: rgba(211, 47, 47, 0.2);
  transform: scale(1.02);
  box-shadow: 0 2px 8px rgba(244, 67, 54, 0.3);
}

.coordinate-box.clickable .button-label {
  background: #f44336;
  color: white;
}

.coordinate-box.clickable:hover .button-label {
  opacity: 1;
}

.coordinate-box.no-next {
  opacity: 0.5;
  cursor: not-allowed;
  border-color: #d9d9d9;
  background: rgba(0, 0, 0, 0.05);
}

.coordinate-box.no-next .button-label {
  background: #8c8c8c;
  color: white;
}

.coordinate-box.no-next:hover .button-label {
  opacity: 1;
}


/* 绘制模式样式 */
.image-wrapper.draw-mode {
  cursor: crosshair;
}

.image-wrapper.draw-mode .coordinate-box {
  pointer-events: none;
  opacity: 0.7;
}

/* 绘制预览框 */
.draw-preview-box {
  position: absolute;
  border: 2px dashed #f44336;
  background: rgba(244, 67, 54, 0.1);
  pointer-events: none;
  min-width: 1px;
  min-height: 1px;
}

.draw-preview-label {
  position: absolute;
  top: -24px;
  left: 0;
  background: #1890ff;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  pointer-events: none;
}

/* 右侧属性面板 */
.properties-panel {
  width: 320px;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #e4e7ed;
}

.panel-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.panel-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

.panel-actions {
  display: flex;
  gap: 8px;
}

.add-button-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #ffffff;
  color: #333333;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.add-button-btn:hover {
  background: #e8f5e8;
  border-color: #4caf50;
  color: #4caf50;
}

.draw-button-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #ffffff;
  color: #333333;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.draw-button-btn:hover {
  background: #e3f2fd;
  border-color: #2196f3;
  color: #2196f3;
}

.draw-button-btn.active {
  background: #ffebee;
  border-color: #f44336;
  color: #f44336;
}

.draw-button-btn.active:hover {
  background: #ffcdd2;
  border-color: #f44336;
  color: #f44336;
}

/* 控件库区域 */
.widget-library-section {
  padding: 12px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.widget-library-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #ffffff;
  color: #333333;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.widget-library-btn:hover {
  background: #f0f5ff;
  border-color: #1890ff;
  color: #1890ff;
}

/* 控件库对话框 */
.widget-library-dialog {
  border-radius: 8px;
}

.widget-library-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-box {
  padding: 0;
}

.widget-list {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.widget-item {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s ease;
}

.widget-item:last-child {
  border-bottom: none;
}

.widget-item:hover {
  background: #f5f7fa;
}

.widget-item.selected {
  background: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.widget-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.widget-name {
  font-size: 15px;
  font-weight: 500;
  color: #262626;
}

.widget-details {
  display: flex;
  gap: 12px;
  font-size: 13px;
  color: #8c8c8c;
}

.widget-size {
  color: #595959;
}

.widget-position {
  color: #722ed1;
  font-weight: 500;
}

.widget-count {
  color: #52c41a;
  font-weight: 500;
}

.widget-next {
  color: #1890ff;
}

.empty-widget {
  padding: 40px 20px;
  text-align: center;
}

/* 智能删除对话框 */
.delete-dialog {
  border-radius: 8px;
}

.delete-dialog-content {
  padding: 8px 0;
}

.delete-info {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  padding: 0 4px;
}

.warning-icon {
  font-size: 24px;
  color: #faad14;
  flex-shrink: 0;
  margin-top: 2px;
}

.delete-text {
  flex: 1;
}

.main-text {
  font-size: 15px;
  color: #262626;
  margin: 0 0 8px 0;
  line-height: 1.5;
}

.main-text strong {
  color: #f5222d;
  font-weight: 600;
}

.sub-text {
  font-size: 13px;
  color: #8c8c8c;
  margin: 0;
}

.delete-options {
  padding: 0 4px;
}

.delete-radio-group {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.delete-radio {
  width: 100%;
  margin: 0;
  padding: 16px 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.2s ease;
  min-height: 60px;
  display: flex;
  align-items: center;
}

.delete-radio:hover {
  border-color: #1890ff;
  background: #f6ffed;
}

.delete-radio.is-checked {
  border-color: #1890ff;
  background: #e6f7ff;
}

.radio-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.radio-title {
  font-size: 15px;
  font-weight: 500;
  color: #262626;
  line-height: 1.5;
}

.radio-desc {
  font-size: 13px;
  color: #8c8c8c;
  line-height: 1.4;
}

.pages-list {
  margin-top: 20px;
  padding: 12px;
  background: #fafafa;
  border-radius: 4px;
}

.pages-title {
  font-size: 13px;
  color: #595959;
  margin-bottom: 12px;
  font-weight: 500;
}

.pages-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.page-tag {
  font-size: 12px;
}

/* 页面选择器 */
.page-selector {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.selector-header {
  margin-bottom: 12px;
}

.page-list-container {
  max-height: 300px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  padding: 8px;
}

.page-item {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 10px;
}

.page-item:hover {
  background: #f0f7ff;
}

.page-item.selected {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
}

.page-item.current {
  background: #fff7e6;
}

.page-item.current.selected {
  background: #ffe7ba;
  border: 1px solid #ffc069;
}

.page-item-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-name {
  font-size: 14px;
  color: #262626;
}

.current-badge {
  display: inline-block;
  padding: 2px 8px;
  background: #ff9800;
  color: #fff;
  border-radius: 3px;
  font-size: 12px;
  font-weight: 500;
}

.empty-pages {
  padding: 40px 0;
  text-align: center;
}

.selector-footer {
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 4px 0;
  border-top: 1px solid #e8e8e8;
}

.selected-count {
  font-size: 13px;
  color: #666;
}

/* 按钮列表 */
.button-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.button-item {
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
  transition: all 0.2s ease;
}

.button-item:hover,
.button-item.active {
  border-color: #1890ff;
  background: #f6ffed;
}

.button-header {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
}

.button-title {
  font-weight: 500;
  color: #262626;
}

.delete-button-btn {
  padding: 4px;
  background: #ff4d4f;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  transition: all 0.2s ease;
}

.delete-button-btn:hover {
  background: #ff7875;
}

/* 属性编辑表单 */
.button-properties {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: white;
}

.property-group {
  margin-bottom: 16px;
}

.property-group label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  color: #595959;
  font-weight: 500;
}

.coordinate-inputs {
  margin-top: 16px;
}

.input-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.input-group {
  flex: 1;
}

.input-group label {
  margin-bottom: 4px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .properties-panel {
    width: 280px;
  }
  
  .image-wrapper {
    min-width: 1000px;
    min-height: 600px;
  }
}

/* 滚动条样式 */
.button-list::-webkit-scrollbar {
  width: 6px;
}

.button-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.button-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.button-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
